/**
 * Created With IntelliJ IDEA
 * Description:leetcode：106. 从中序与后序遍历序列构造二叉树
 * <a href="https://leetcode.cn/problems/construct-binary-tree-from-inorder-and-postorder-traversal/">...</a>
 * User: DELL
 * Data: 2023-01-14
 * Time: 20:29
 */

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    public TreeNode(int val) {
        this.val = val;
    }
}
//题目规定：1 <= inorder.length <= 3000
//        postorder.length == inorder.length
//        -3000 <= inorder[i], postorder[i] <= 3000
//        inorder和postorder都由不同的值组成
//        postorder中每一个值都在inorder中
//        inorder保证是树的中序遍历
//        postorder保证是树的后序遍历
public class Solution {
    private int i;

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.i = postorder.length - 1;
        return buildSubTree(inorder, postorder, 0, inorder.length - 1);
    }

    private TreeNode buildSubTree(int[] inorder, int[] postorder, int inBegin, int inLast) {
        if (inBegin > inLast) {
            return null;
        }
        //构建根节点
        int val = postorder[i];
        i--;
        TreeNode root = new TreeNode(val);
        //寻找inorder中值为val的下标
        int temp = 0;
        for (int j = inBegin; j <= inLast; j++) { //这里是j<=inLast,很关键
            if (inorder[j] == val) {
                temp = j;
                break;
            }
        }
        //构建左右子树
        root.right = buildSubTree(inorder, postorder, temp + 1, inLast);
        root.left = buildSubTree(inorder, postorder, inBegin, temp - 1);
        //返回根节点
        return root;
    }
}